package sql

// 大小写转换过滤器
import (
	"regexp"
	"strings"

	"github.com/xormplus/core"
)

type OracleUpperFilter struct {
	do func(sql string, dialect core.Dialect, table *core.Table) string
}

func (s *OracleUpperFilter) _do() func(sql string, dialect core.Dialect, table *core.Table) string {

	var _id = regexp.MustCompile("([\\s\\.=<>\\|,\\(])(_[A-Z][A-Za-z0-9_]*)([\\s\\.=<>\\|,\\)]|$)")
	var keywords1 = regexp.MustCompile("([\\s\\.=<>\\|,\\(])(ACCESS|USER|LEVEL)([\\s\\.=<>\\|,\\)]|$)")
	var keywords2 = regexp.MustCompile("([\\s\\.=<>\\|,\\(])(GROUP|ORDER)([\\.=<>\\|,\\)]|$)")
	var notGroupBy = regexp.MustCompile("([\\s\\.=<>\\|,\\(])(GROUP|ORDER)(\\s+[^B][^Y])")
	var as = regexp.MustCompile("(\\s)AS(\\s)")
	var ifnull = regexp.MustCompile("([\\s\\.=<>\\|,\\(])IFNULL(\\s|\\()")

	return func(sql string, dialect core.Dialect, table *core.Table) string {

		sql = strings.ToUpper(sql)
		sql = _id.ReplaceAllString(sql, `$1"$2"$3`)
		sql = keywords1.ReplaceAllString(sql, `$1"$2"$3`)
		sql = as.ReplaceAllString(sql, `$1$2`)
		sql = keywords2.ReplaceAllString(sql, `$1"$2"$3`)
		sql = notGroupBy.ReplaceAllString(sql, `$1"$2"$3`)
		sql = strings.Replace(sql, "`", `"`, -1)
		sql = ifnull.ReplaceAllString(sql, "$1 NVL $2")
		return sql
	}
}

func (s *OracleUpperFilter) Do(sql string, dialect core.Dialect, table *core.Table) string {

	if s.do == nil {
		s.do = s._do()
	}

	return s.do(sql, dialect, table)
}
